<template>
  <div class="view-fill">
    <div
      v-if="!modifyInfo.visible && !templateModifyInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button
            v-if="setBtnStatus(1) && $permission('useApplication:submit')"
            :plain="true"
            @click="submit"
            >提交</el-button
          >
          <el-button v-if="canSplit" :plain="true" @click="handelMethodSplit"
            >拆单</el-button
          >
          <el-button
            v-if="
              $permission('useApplication:update') && infoList.data.status === 1
            "
            :plain="true"
            @click="update"
            >修改</el-button
          >
          <el-button
            v-if="
              infoList.data.status === 2 &&
              $permission('useApplication:retract')
            "
            :plain="true"
            @click="retract"
            >撤回</el-button
          >
          <el-button
            v-if="
              infoList.data.status !== 1 &&
              $permission('useApplication:exportExcel')
            "
            :plain="true"
            @click="exportExcel"
            >导出excel</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canComplete"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button
            v-if="$permission('useApplicationOrder:saveCopeTemplate')"
            :plain="true"
            @click="saveCopeTemplate"
            >另存为模板</el-button
          >
          <el-button
            v-if="$permission('useApplicationOrder:copy')"
            :plain="true"
            @click="copyUseApplicationOrder"
            >拷贝</el-button
          >
          <!--        <el-button  :plain="true" @click="print">打印</el-button>-->
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information
              :info="infoList"
              :label-width="infoList.labelWidth"
            >
              <template v-slot:basic-mergedOrders>
                <span
                  v-if="
                    infoList.data.mergedOrders &&
                    infoList.data.mergedOrders.length <= 3
                  "
                >
                  <span
                    v-for="(item, itemIndex) in infoList.data.mergedOrders"
                    :key="itemIndex"
                  >
                    <a class="slip-edit" @click="getNew(item.id)">{{
                      item.orderNo
                    }}</a>
                    <span
                      v-if="itemIndex < infoList.data.mergedOrders.length - 1"
                      >,</span
                    >
                  </span>
                </span>
                <span
                  v-if="
                    infoList.data.mergedOrders &&
                    infoList.data.mergedOrders.length > 3
                  "
                >
                  <span
                    v-for="(
                      item, itemIndex
                    ) in infoList.data.mergedOrders.slice(0, 2)"
                    :key="itemIndex"
                  >
                    <a class="slip-edit" @click="getNew(item.id)">{{
                      item.orderNo
                    }}</a>
                    <span v-if="itemIndex < 1">,</span>
                  </span>
                  <el-dropdown @command="handleCommand">
                    <span class="el-dropdown-link slip-edit">
                      更多<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="(
                            item, index
                          ) in infoList.data.mergedOrders.slice(
                            2,
                            infoList.data.mergedOrders.length
                          )"
                          :key="index"
                          :command="item.id"
                          >{{ item.orderNo }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </span>
              </template>
              <template v-slot:basic-mergedOrder>
                <a
                  v-if="infoList.data.mergeOrder"
                  class="slip-edit"
                  @click="getNew(infoList.data.mergeOrder.id)"
                  >{{ infoList.data.mergeOrder.orderNo }}</a
                >
              </template>
            </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title div-flex">
            <Tooltip :text="$t('detailInfo')" />
            <modelTips
              :items="modelTipsInfo.items"
              :title="modelTipsInfo.title"
              :brackets="true"
            />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <div class="flex_full_item">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :check-box="false"
                  :tab-index="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isDynamic="true"
                >
                  <template v-slot:col-purch="scope">
                    <p>
                      {{
                        (scope.row.applicationQty
                          ? scope.row.applicationQty
                          : 0) + (scope.row.purchQty ? scope.row.purchQty : 0)
                      }}
                    </p>
                    <p>{{ scope.row.cancelQty || 0 }}</p>
                  </template>
                </page-table>
              </div>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <use-application-modify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :is-copy="modifyInfo.isCopy"
    />
    <TemplateModify
      v-if="templateModifyInfo.visible"
      v-model:visible="templateModifyInfo.visible"
      :useApplicationOrderId="templateModifyInfo.useApplicationOrderId"
      :title="templateModifyInfo.title"
    />
  </div>
</template>

<script setup name="useApplicationDetails">
import BasicInformation from '@/components/BasicInformation/index'
import {
  detailUseApplication,
  getUseApplicationDetailCustomizeList,
  exportUseApplication,
  getApplicationPrint,
  submitUseApplication,
  deleteUseApplication,
  retractUseApplication,
  useApplicationSplit,
  applicationValidateSubDepot,
} from '@/api/use.js'
const UseApplicationModify = defineAsyncComponent(() => import('./modify'))
const TemplateModify = defineAsyncComponent(() => import('../template/modify'))

import { getCustomizeSetting } from '@/api/customize'
import utils from '@/common/js/utils'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'id'])

const modelTipsInfo = reactive({
  title: '高水位预警',
  items: [
    {
      label: '超过',
      style: { width: '10px', height: '10px', background: '#f7c1c1' },
    },
  ],
})
const title = '领用单详情'
const infoList = reactive({
  data: {},
  fieldList: [
    { label: '领用申请单号', value: 'orderNo', type: 'text' },
    { label: '领用人', value: 'createUserName', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '领用部门', value: 'deptName', type: 'text' },
    { label: '领出部门', value: 'exportDeptName', type: 'text' },
    { label: '领出仓库', value: 'exportDepotName', type: 'text' },
    { label: '领入仓库', value: 'depotName', type: 'text' },
    { label: '领用日期', value: 'applicationTime', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '更新人', value: 'updateUserName', type: 'text' },
    { label: '更新时间', value: 'updateTime', type: 'text' },
    { label: '新订单号', value: 'mergedOrder', type: 'slot' },
    { label: '原订单号', value: 'mergedOrders', type: 'slot' },
    { label: '备注', value: 'remark', type: 'text' },
  ],
  labelWidth: '130px',
})
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
})
//另存为模板参数
const templateModifyInfo = reactive({
  visible: false,
  useApplicationOrderId: '',
  title: '另存为模板',
})
const affairTableInfo = reactive({
  query: {
    orderType: 19,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
const exportInfo = reactive({
  visible: false,
  title: '领用单出库',
  id: '',
})
const storageInfo = reactive({
  visible: false,
  title: '领用单入库',
  id: '',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
  },
})
//更新相关/////
const modifyInfo = reactive({
  visible: false,
  title: '',
  id: '',
  isCopy: false,
})

const canComplete = computed(() => {
  return infoList.data.status !== 1 && proxy.$permission('useApplication:print')
})
const canSplit = computed(() => {
  return (
    proxy.$permission('useApplicationOrder:split') &&
    (infoList.data.status === 1 || infoList.data.status === 2) &&
    infoList.data.mergedOrders.length > 0 &&
    infoList.data.status === infoList.data.beforeMergeStatus
  )
})

const showDialog = computed({
  get() {
    console.log(props.visible, 'props.visible')
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => props.id,
  (newVal) => {
    filterInfo.query.queryMap.orderId.value = newVal
    affairTableInfo.query.orderId = newVal
    setData()
    getCustomize()
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => modifyInfo.visible,
  (value) => {
    if (!value) {
      getMain()
    }
  }
)
function setData() {
  let obj = {
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      type: 'column',
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      minWidth: '150px',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('useApplication:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('useApplication:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      componentType: 'price',
      permission: !proxy.$permission('useApplication:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
    preExportQty: {
      label: '预出库数量',
      value: 'preExportQty',
      type: 'column',
      show: false,
      hidden: true,
    },
    storeStockQty: {
      label: '领入仓库可用数量',
      value: 'storeStockQty',
      hidden: true,
      type: 'column',
      formatter: utils.qtyFormatter,
    },
    exportStockQty: {
      label: '领出仓库可用数量',
      value: 'exportStockQty',
      hidden: true,
      type: 'column',
      formatter: utils.qtyFormatter,
    },
    exportQty: {
      label: '出库数量',
      value: 'exportQty',
      type: 'column',
      show: false,
      hidden: true,
    },
    storeQty: {
      label: '入库数量',
      value: 'storeQty',
      type: 'column',
      show: false,
      hidden: true,
    },
    availableQty: {
      label: '可出库数量',
      value: 'availableQty',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
}
function tableRowClassName({ row }) {
  if (row.hasOwnProperty('depotStockHighQty')) {
    let qty = proxy.$fn.accDiv(
      proxy.$fn.accAdd(row.calcQty || 0, row.depotStockCalcQty),
      row.unitConvertCoefficient
    )
    if (qty > row.depotStockHighQty) {
      return 'warning-row'
    } else {
      return ''
    }
  }
  return ''
}
function handelMethodSplit() {
  const ids = []
  ids.push(props.id)
  useApplicationSplit(ids).then((resp) => {
    if (resp.success) {
      getMain()
    }
  })
}
function getNew(id) {
  filterInfo.query.queryMap.orderId.value = id
  affairTableInfo.query.orderId = id
  props.id = id
  getMain()
}
function handleCommand(id) {
  getNew(id)
}
//拷贝
function copyUseApplicationOrder() {
  applicationValidateSubDepot(infoList.data).then((res) => {
    if (res && res.success) {
      modifyInfo.visible = true
      modifyInfo.isCopy = true
      modifyInfo.title = '拷贝领用单'
      modifyInfo.id = props.id
    }
  })
}
//另存为模板
function saveCopeTemplate() {
  templateModifyInfo.visible = true
  templateModifyInfo.useApplicationOrderId = props.id
}
function returnBack() {
  emit('returnBack', false)
}
//出库
function _export() {
  exportInfo.visible = true
  exportInfo.id = props.id
}
//入库
function storage() {
  storageInfo.visible = true
  storageInfo.id = props.id
}
//提交
function submit() {
  const ids = []
  ids.push(props.id)
  submitUseApplication(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
    }
  })
}

// 编辑
function update() {
  modifyInfo.id = props.id
  modifyInfo.visible = true
  modifyInfo.title = '修改领用单'
}
// 删除*
function _delete() {
  if (infoList.data.status != 1) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '当前数据状态无法删除',
    })
  } else {
    proxy.$handleAPI('delete', deleteUseApplication, [props.id]).then((res) => {
      if (res.success) {
        getMain()
      }
    })
  }
}
//撤回*
function retract() {
  const ids = []
  ids.push(props.id)
  retractUseApplication(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
    }
  })
}

function getList() {
  getUseApplicationDetailCustomizeList(filterInfo.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.data = resp.data
    }
  })
}
function setBtnStatus(str) {
  let data = infoList.data
  if (str === 1) {
    return data.status === 1
  } else if (str === 'rejected') {
    return data.status === 'rejected' || data.status === 1
  } else if (str === 2) {
    return data.status === 2
  }
}
//导出excel
function exportExcel() {
  exportUseApplication(filterInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'useApplicationDetail',
    deptId: infoList.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: infoList.data.id,
            orderId: infoList.data.id,
            orderNo: infoList.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: infoList.data.id,
      orderId: infoList.data.id,
      orderNo: infoList.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.data.orderNo,
      orderId: infoList.data.id,
      tempCode: 'useApplicationDetail',
      orderType: 19,
    })
  } catch (error) {}
}

function getPirntData(temp) {
  let params = {
    tableKey:
      'useApplicationOrderDetail-com.slip.spd.entity.vo.use.UseApplicationOrderDetailVO',
    orderIds: [props.id],
  }
  getApplicationPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('useApplication:price')
      )
    }
  })
}
function getMain() {
  detailUseApplication(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.data = resp.data
      getList()
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'useApplicationOrderDetail-com.slip.spd.entity.vo.use.UseApplicationOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      getMain()
    }
  })
}
</script>

<style scoped></style>
